class Solution {
    public int calculate(String s) {
        Stack<Integer> num_stack = new Stack();  //数据栈
        int num = 0;
        boolean changed = false;   //数字是否改变
        boolean neg = false;   //前面是否是负号，如果是true，要变为相反数

        for(int i=0 ; i<s.length(); i++) {
            String ch = s.substring(i,i+1);
            if(ch.equals(" ")) {   //这个位置是空格
                if(changed == true) { //如果前一个是数，那么到这个空格，这个数已经结束了，应该入栈
                    if(neg == true) num = -num;  
                    num_stack.push(num);
                    changed = false;
                    neg = false;
                    num = 0;
                }
                continue;
            }
            else if(!ch.equals("*") && !ch.equals("/")) {
                if(ch.equals("+")) {   //加号和减号不同的地方在于neg的值
                    if(changed == true) {
                        if(neg == true) num = -num;
                        num_stack.push(num);
                        num = 0;
                        changed = false;
                        neg = false;
                    }                                 
                }  
                else if(ch.equals("-")) {
                    if(changed == true) {
                        if(neg == true) num = -num;
                        num_stack.push(num);
                        num = 0;
                        changed = false;
                    }
                    neg = true;
                }
                else {  //是数字
                    num = num*10 + Integer.parseInt(ch);
                    changed = true;
                }
            }
            else { //如果是乘除
                int next = 0, last  = 0;
                if(changed == false) last = num_stack.pop();
                else last = num;
                num = 0;
                changed = false;
                if(neg == true) last = - last;
                neg = false;
                i++;
                while(i<s.length() && s.charAt(i) == ' ') i++;   //去掉空格
                while(i<s.length() && s.charAt(i)>='0' && s.charAt(i) <= '9') {           
                    next = next*10 + Integer.parseInt(s.substring(i,i+1));
                    i++;
                }
                if(ch.equals("*")) num_stack.push(last*next);
                else num_stack.push(last/next);
                i--;
            }
        }
        
        if(changed == true) {     //最后还有一个数还没有入栈
            if(neg == true) num = -num;  //仍然需要判断是否前面有负号
            num_stack.push(num);
        }

		//此时符号栈中只有加号，将数依次加起来即可
        int ans = 0;
        while(!num_stack.empty()) {
            ans += num_stack.pop();
        }
        return ans;
    }
}